package server;

import java.io.IOException;
import java.io.InputStream;

/**
 * 把请求信息封装为Request对象（根据inputStream输入流进行封装）
 */
public class Request {

    private String method; // 请求方式， 比如去GET/POST
    private String url; // 请求路径， 例如 /, /index.html

    private InputStream inputStream;

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public Request() {
    }

    // 构造器， 输入流传入
    public Request(InputStream inputStream) throws IOException {
        this.inputStream = inputStream;

        // 从输入流中获取请求信息
        int count = 0;
        long start = System.currentTimeMillis();
        while(count == 0) {
            count = inputStream.available();
            //如果自旋锁超过10毫秒， 自动释放锁， 避免一直阻塞
            if(System.currentTimeMillis() - start > 10) return;
        }
        byte[] bytes = new byte[count];
        inputStream.read(bytes);

        String inputStr = new String(bytes);
        //获取第一行请求头信息
        String firstLineStr = inputStr.split("\\n")[0];

        String[] strings = firstLineStr.split(" "); // GET / HTTP/1.1
        this.method = strings[0];
        this.url = strings[1];

        System.out.println("=======>>>>>method:" + this.method);
        System.out.println("=======>>>>>url:" + this.url);


    }

}
